{% extends "base.html" %}

{% block title %}首页 - 慢性病风险预测与智能干预系统{% endblock %}

{% block content %}
<!-- 欢迎横幅 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body text-center py-5">
                <h1 class="display-4 mb-3">
                    <i class="fas fa-heartbeat text-primary me-3"></i>
                    慢性病风险预测与智能干预系统
                </h1>
                <p class="lead text-muted mb-4">
                    基于多源数据的AI健康管理平台，融合XGBoost与LSTM技术，
                    为高血压、2型糖尿病等慢性病提供精准风险预测与个性化干预建议
                </p>
                <div class="row justify-content-center">
                    <div class="col-md-8">
                        <div class="row text-center">
                            <div class="col-md-4 mb-3">
                                <div class="p-3">
                                    <i class="fas fa-brain fa-2x text-primary mb-2"></i>
                                    <h5>AI智能预测</h5>
                                    <p class="text-muted small">准确率≥85%</p>
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <div class="p-3">
                                    <i class="fas fa-chart-line fa-2x text-success mb-2"></i>
                                    <h5>多源数据融合</h5>
                                    <p class="text-muted small">结构化+时序数据</p>
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <div class="p-3">
                                    <i class="fas fa-user-md fa-2x text-warning mb-2"></i>
                                    <h5>权威医学指南</h5>
                                    <p class="text-muted small">循证医学依据</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 快速预测表单 -->
<div class="row mb-4">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-calculator me-2"></i>
                    快速风险预测
                </h5>
            </div>
            <div class="card-body">
                <form id="predictionForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="age" class="form-label">年龄</label>
                                <input type="number" class="form-control" id="age" name="age" min="18" max="100" value="45" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="gender" class="form-label">性别</label>
                                <select class="form-select" id="gender" name="gender" required>
                                    <option value="male">男性</option>
                                    <option value="female">女性</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="height" class="form-label">身高 (cm)</label>
                                <input type="number" class="form-control" id="height" name="height" min="120" max="220" value="170" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="weight" class="form-label">体重 (kg)</label>
                                <input type="number" class="form-control" id="weight" name="weight" min="30" max="200" value="70" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="systolic_bp" class="form-label">收缩压 (mmHg)</label>
                                <input type="number" class="form-control" id="systolic_bp" name="systolic_bp" min="80" max="250" value="120" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="diastolic_bp" class="form-label">舒张压 (mmHg)</label>
                                <input type="number" class="form-control" id="diastolic_bp" name="diastolic_bp" min="50" max="150" value="80" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="blood_glucose" class="form-label">空腹血糖 (mg/dL)</label>
                                <input type="number" class="form-control" id="blood_glucose" name="blood_glucose" min="50" max="300" value="100" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="heart_rate" class="form-label">心率 (次/分钟)</label>
                                <input type="number" class="form-control" id="heart_rate" name="heart_rate" min="40" max="200" value="72" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">生活方式</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="smoking" name="smoking">
                                    <label class="form-check-label" for="smoking">吸烟</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="drinking" name="drinking">
                                    <label class="form-check-label" for="drinking">饮酒</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="family_history" name="family_history">
                                    <label class="form-check-label" for="family_history">家族史</label>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="exercise_frequency" class="form-label">运动频率</label>
                                <select class="form-select" id="exercise_frequency" name="exercise_frequency">
                                    <option value="never">从不运动</option>
                                    <option value="occasionally" selected>偶尔运动</option>
                                    <option value="regularly">经常运动</option>
                                    <option value="daily">每天运动</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="text-center">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="fas fa-search me-2"></i>
                            开始预测
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 预测结果 -->
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-chart-pie me-2"></i>
                    预测结果
                </h5>
            </div>
            <div class="card-body" id="predictionResult">
                <div class="text-center text-muted">
                    <i class="fas fa-info-circle fa-2x mb-3"></i>
                    <p>请填写左侧表单并点击"开始预测"按钮</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 系统特性介绍 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-star me-2"></i>
                    系统特性
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 col-lg-3 mb-4">
                        <div class="text-center">
                            <div class="bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 60px; height: 60px;">
                                <i class="fas fa-database fa-lg"></i>
                            </div>
                            <h6>多源数据融合</h6>
                            <p class="text-muted small">整合个体基础数据、时序生理指标、生活方式数据，构建全面的健康画像</p>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-3 mb-4">
                        <div class="text-center">
                            <div class="bg-success text-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 60px; height: 60px;">
                                <i class="fas fa-robot fa-lg"></i>
                            </div>
                            <h6>AI模型融合</h6>
                            <p class="text-muted small">XGBoost处理结构化特征，LSTM捕捉时序趋势，预测准确率达85%以上</p>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-3 mb-4">
                        <div class="text-center">
                            <div class="bg-warning text-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 60px; height: 60px;">
                                <i class="fas fa-lightbulb fa-lg"></i>
                            </div>
                            <h6>可解释AI</h6>
                            <p class="text-muted small">通过SHAP值可视化关键风险因素，让AI决策过程透明可理解</p>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-3 mb-4">
                        <div class="text-center">
                            <div class="bg-info text-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 60px; height: 60px;">
                                <i class="fas fa-book-medical fa-lg"></i>
                            </div>
                            <h6>权威医学指南</h6>
                            <p class="text-muted small">干预建议基于《中国高血压防治指南》等权威文献，确保科学性</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 应用场景 -->
<div class="row">
    <div class="col-md-6">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-hospital me-2"></i>
                    基层医疗场景
                </h5>
            </div>
            <div class="card-body">
                <ul class="list-unstyled">
                    <li class="mb-2">
                        <i class="fas fa-check-circle text-success me-2"></i>
                        辅助家庭医生快速筛查高危人群
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-check-circle text-success me-2"></i>
                        生成个性化风险等级报告
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-check-circle text-success me-2"></i>
                        提供循证医学干预建议
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-check-circle text-success me-2"></i>
                        支持群体健康管理分析
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-user me-2"></i>
                    个人健康管理
                </h5>
            </div>
            <div class="card-body">
                <ul class="list-unstyled">
                    <li class="mb-2">
                        <i class="fas fa-check-circle text-success me-2"></i>
                        实时评估个人患病风险
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-check-circle text-success me-2"></i>
                        获取个性化生活方式建议
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-check-circle text-success me-2"></i>
                        支持可穿戴设备数据导入
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-check-circle text-success me-2"></i>
                        可视化健康指标变化趋势
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 表单提交处理
    $('#predictionForm').on('submit', function(e) {
        e.preventDefault();
        
        // 收集表单数据
        const formData = {
            age: parseInt($('#age').val()),
            gender: $('#gender').val(),
            height: parseInt($('#height').val()),
            weight: parseInt($('#weight').val()),
            systolic_bp: parseInt($('#systolic_bp').val()),
            diastolic_bp: parseInt($('#diastolic_bp').val()),
            blood_glucose: parseInt($('#blood_glucose').val()),
            heart_rate: parseInt($('#heart_rate').val()),
            smoking: $('#smoking').is(':checked'),
            drinking: $('#drinking').is(':checked'),
            family_history: $('#family_history').is(':checked'),
            exercise_frequency: $('#exercise_frequency').val()
        };
        
        // 显示加载状态
        showLoading('#predictionResult');
        
        // 发送预测请求
        $.ajax({
            url: '/api/predict',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                if (response.success) {
                    displayPredictionResult(response);
                } else {
                    showAlert('预测失败：' + response.error, 'danger');
                    hideLoading('#predictionResult', '<div class="text-center text-muted"><i class="fas fa-exclamation-triangle fa-2x mb-3"></i><p>预测失败，请重试</p></div>');
                }
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON ? xhr.responseJSON.error : '网络错误';
                showAlert('预测失败：' + errorMsg, 'danger');
                hideLoading('#predictionResult', '<div class="text-center text-muted"><i class="fas fa-exclamation-triangle fa-2x mb-3"></i><p>预测失败，请重试</p></div>');
            }
        });
    });
    
    // 显示预测结果
    function displayPredictionResult(response) {
        const prediction = response.prediction;
        const explanation = response.shap_explanation;
        const interventions = response.intervention_suggestions;
        
        let resultHtml = `
            <div class="mb-3">
                <h6 class="text-primary">综合风险评估</h6>
                <div class="text-center mb-3">
                    <div class="display-6 ${prediction.overall_risk.risk_level === 'high' ? 'text-danger' : prediction.overall_risk.risk_level === 'medium' ? 'text-warning' : 'text-success'}">
                        ${formatProbability(prediction.overall_risk.probability)}
                    </div>
                    <div>${formatRiskLevel(prediction.overall_risk.risk_level)}</div>
                </div>
            </div>
            
            <div class="mb-3">
                <h6 class="text-primary">疾病风险分析</h6>
                <div class="row">
                    <div class="col-6">
                        <div class="text-center">
                            <div class="h5 ${prediction.hypertension_risk.risk_level === 'high' ? 'text-danger' : prediction.hypertension_risk.risk_level === 'medium' ? 'text-warning' : 'text-success'}">
                                ${formatProbability(prediction.hypertension_risk.probability)}
                            </div>
                            <small class="text-muted">高血压风险</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="text-center">
                            <div class="h5 ${prediction.diabetes_risk.risk_level === 'high' ? 'text-danger' : prediction.diabetes_risk.risk_level === 'medium' ? 'text-warning' : 'text-success'}">
                                ${formatProbability(prediction.diabetes_risk.probability)}
                            </div>
                            <small class="text-muted">糖尿病风险</small>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="mb-3">
                <h6 class="text-primary">主要风险因素</h6>
                <div id="riskFactors">
        `;
        
        if (explanation.top_risk_factors && explanation.top_risk_factors.length > 0) {
            explanation.top_risk_factors.forEach(factor => {
                resultHtml += `
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span>${factor.display_name}</span>
                        <div class="feature-importance-bar" style="width: ${factor.importance * 100}%"></div>
                    </div>
                `;
            });
        }
        
        resultHtml += `
                </div>
            </div>
            
            <div class="text-center">
                <button class="btn btn-outline-primary btn-sm" onclick="showDetailedResults()">
                    <i class="fas fa-info-circle me-1"></i>
                    查看详细分析
                </button>
            </div>
        `;
        
        hideLoading('#predictionResult', resultHtml);
        
        // 存储详细结果供后续使用
        window.detailedResults = {
            prediction: prediction,
            explanation: explanation,
            interventions: interventions
        };
    }
    
    // 显示详细结果
    window.showDetailedResults = function() {
        if (!window.detailedResults) return;
        
        const { prediction, explanation, interventions } = window.detailedResults;
        
        // 创建模态框
        const modalHtml = `
            <div class="modal fade" id="detailedModal" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">详细分析结果</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>时间跨度预测</h6>
                                    <div class="table-responsive">
                                        <table class="table table-sm">
                                            <thead>
                                                <tr>
                                                    <th>时间</th>
                                                    <th>高血压风险</th>
                                                    <th>糖尿病风险</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>1年</td>
                                                    <td>${formatProbability(prediction.time_predictions['1_year'].hypertension_risk)}</td>
                                                    <td>${formatProbability(prediction.time_predictions['1_year'].diabetes_risk)}</td>
                                                </tr>
                                                <tr>
                                                    <td>3年</td>
                                                    <td>${formatProbability(prediction.time_predictions['3_years'].hypertension_risk)}</td>
                                                    <td>${formatProbability(prediction.time_predictions['3_years'].diabetes_risk)}</td>
                                                </tr>
                                                <tr>
                                                    <td>5年</td>
                                                    <td>${formatProbability(prediction.time_predictions['5_years'].hypertension_risk)}</td>
                                                    <td>${formatProbability(prediction.time_predictions['5_years'].diabetes_risk)}</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <h6>AI解释</h6>
                                    <p class="small">${explanation.explanation_text}</p>
                                    
                                    <h6>干预建议</h6>
                                    <div class="intervention-card">
                                        <h6>${interventions.overall_recommendation.title}</h6>
                                        <p class="small">${interventions.overall_recommendation.summary}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                            <a href="/user" class="btn btn-primary">进入用户端</a>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除已存在的模态框
        $('#detailedModal').remove();
        
        // 添加新模态框
        $('body').append(modalHtml);
        
        // 显示模态框
        $('#detailedModal').modal('show');
    };
});
</script>
{% endblock %}
